package end.util.jedis;

import java.io.Serializable;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.commons.lang3.SerializationUtils;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.CacheException;

import redis.clients.jedis.Jedis;

/**
 * 
 * RedisCache.java 2016-7-12
 * 
 * Copyright zhaocj Inc. All rights reserved. Love Me Like Love Justin Bieber
 */

public class IbatisRedisCache implements Cache {
	private String id;

	private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

	public IbatisRedisCache(String id) {
		this.id = id;
	}

	@Override
	public void clear() {
		Jedis jedis = JedisPoolUtils.getJedis();
		try {
			jedis.select(3);
			jedis.flushDB();
		} catch (Exception e) {
			throw new CacheException(e);
		} finally {
			JedisPoolUtils.close(jedis);
		}
	}

	@Override
	public String getId() {
		return id;
	}

	@Override
	public Object getObject(Object key) {
		Jedis jedis = JedisPoolUtils.getJedis();
		try {
			jedis.select(3);
			byte[] bs = jedis.get(SerializationUtils
					.serialize((Serializable) key));
			if (bs == null) {
				return null;
			}
			return SerializationUtils.deserialize(bs);
		} catch (Exception e) {
			throw new CacheException(e);
		} finally {
			JedisPoolUtils.close(jedis);
		}
	}

	@Override
	public ReadWriteLock getReadWriteLock() {
		return readWriteLock;
	}

	@Override
	public int getSize() {
		Jedis jedis = JedisPoolUtils.getJedis();
		try {
			jedis.select(3);
			return jedis.dbSize().intValue();
		} catch (Exception e) {
			throw new CacheException(e);
		} finally {
			JedisPoolUtils.close(jedis);
		}
	}

	@Override
	public void putObject(Object key, Object value) {
		Jedis jedis = JedisPoolUtils.getJedis();
		try {
			jedis.select(3);
			jedis.set(SerializationUtils.serialize((Serializable) key),
					SerializationUtils.serialize((Serializable) value));
		} catch (Exception e) {
			throw new CacheException(e);
		} finally {
			JedisPoolUtils.close(jedis);
		}
	}

	@Override
	public Object removeObject(Object key) {
		Jedis jedis = JedisPoolUtils.getJedis();
		try {
			jedis.select(3);
			byte[] bs = jedis.get(SerializationUtils
					.serialize((Serializable) key));
			jedis.del(SerializationUtils.serialize((Serializable) key));
			if (bs == null) {
				return null;
			}
			return SerializationUtils.deserialize(bs);
		} catch (Exception e) {
			throw new CacheException(e);
		} finally {
			JedisPoolUtils.close(jedis);
		}
	}

}
